import { computed } from 'vue'
import { defineStore } from 'pinia'
import { useSessionStorage, StorageSerializers } from '@vueuse/core'
import { userApi } from '@/api'

export const useUserStore = defineStore('user', () => {
  const expoId = Number(import.meta.env.VITE_EXPO_ID)

  const user = useSessionStorage('user', null, {
    serializer: StorageSerializers.object
  })
  const token = useSessionStorage('token', '')

  const setUser = info => (user.value = info)
  const getUser = async () => {
    return await userApi.getUser()
  }
  const getAndSetUser = async () => {
    const { data } = await getUser({ data: 1 })
    user.value = data
    await getAdminMenus()
  }
  const getAdminMenus = async () => {
    const params = {
      rolesId: user.value.roleId || 1 // 1查所有菜单 , 有id的话是回显的接口
    }
    const {
      data: { project }
    } = await userApi.getRoleMenus(params)
    setMenuList(project)
  }
  const menuList = useSessionStorage('menuList', [])
  const setMenuList = val => (menuList.value = val)
  const setToken = val => (token.value = val)

  const clear = () => {
    setUser(null)
    setToken('')
    setMenuList(null)
  }

  return {
    expoId,
    token,
    user,
    getUser,
    setUser,
    getAndSetUser,
    setToken,
    clear,
    getAdminMenus,
    menuList
  }
})
